package com.tgy.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: tgy
 * @Date: 12/24/20 3:09 PM
 *
 * https://leetcode-cn.com/problems/spiral-matrix/submissions/
 */
public class _54_螺旋矩阵 {

    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> rets = new ArrayList<>();

        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {

            return rets;
        }

        int top = 0, right = matrix[0].length - 1,bottom = matrix.length - 1,left = 0;

        while (left <= right && top <= bottom) {

            for (int i = left; i <= right; i++) {

                rets.add(matrix[top][i]);
            }

            top++;

            for (int i = top; i <=bottom; i++) {
                rets.add(matrix[i][right]);
            }

            right--;

            /**
             * 如果下面成了，则
             * 上面执行时要么 left = right，要么 top = bottom
             */
            if (left > right || top > bottom) {

                break;
            }

            for (int i = right; i >= left ; i--) {
                rets.add(matrix[bottom][i]);
            }

            bottom--;

            for (int i = bottom; i >= top; i--) {

                rets.add(matrix[i][left]);
            }

            left++;
        }


        return rets;
    }
}
